package com.yanyeori.framework.web.filter;

import com.yanyeori.framework.core.model.WebResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationListener;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

/**
 * 自定义filter处理器
 *
 * @author chenkuan 2022/10/27
 */
public abstract class FilterHandler implements ApplicationListener<ApplicationStartedEvent> {
    protected final Logger log = LoggerFactory.getLogger(getClass());

    private static final List<RequestFilter> BEFORE_FILTERS = new ArrayList<>();
    private static final List<RequestFilter> AFTER_FILTERS = new ArrayList<>();

    @Override
    public void onApplicationEvent(ApplicationStartedEvent applicationStartedEvent) {
        this.configure(new FilterManager());
        BEFORE_FILTERS.sort(Comparator.comparing(RequestFilter::getOrder));
        AFTER_FILTERS.sort(Comparator.comparing(RequestFilter::getOrder));
    }

    /**
     * 过滤管理器类
     */
    protected static class FilterManager {
        /**
         * 注入前置请求过滤器
         */
        public FilterManager addBeforeFilter(RequestFilter requestFilter) {
            BEFORE_FILTERS.add(requestFilter);
            return this;
        }

        /**
         * 注入后置请求过滤器
         */
        public FilterManager addAfterFilter(RequestFilter requestFilter) {
            AFTER_FILTERS.add(requestFilter);
            return this;
        }
    }

    /**
     * 执行前置过滤器
     */
    public static WebResponse<?> handleBeforeFilter(HttpServletRequest request, HttpServletResponse response) {
        return handle(BEFORE_FILTERS, request, response);
    }

    /**
     * 执行后置过滤器
     */
    public static WebResponse<?> handleAfterFilter(HttpServletRequest request, HttpServletResponse response) {
        return handle(AFTER_FILTERS, request, response);
    }

    private static WebResponse<?> handle(List<RequestFilter> filters, HttpServletRequest request, HttpServletResponse response) {
        for (RequestFilter filter : filters) {
            if (filter == null) {
                continue;
            }
            WebResponse<?> webResponse = filter.handle(request, response);
            if (webResponse != null && !webResponse.isSuccess()) {
                return webResponse;
            }
        }
        return WebResponse.ok();
    }

    /**
     * 实现此方法以扩展过滤器
     *
     * @param filterManager 过滤管理器
     */
    protected abstract void configure(FilterManager filterManager);
}
